package com.zzb.framework.common;

import com.zzb.framework.query.GenericQueryDAO;
import com.zzb.framework.modules.role.entity.SysUserEntity;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

/**
 * 基本操作的service
 * Created by zhangzhenbin on 17-2-21.
 */
@Component
public abstract class BaseService<DAO extends BaseDAO<T>, T extends BaseEntity>{
    @Autowired
    private GenericQueryDAO genericQueryDAO;

    public Class<T> getClazz(){
        return  (Class <T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1];
    }

    /**
     * 获取实体dao对象
     */
    abstract public DAO getDAO();

    /**
     * 通过用户id获取实体
     */
    public T get(String id) {
        return getDAO().selectById(id);
    }

    /**
     * 回收
     */
    @Transactional
    public BaseResponse<T> trashById(String id, SysUserEntity operator) {
        T t = get(id);
        return trash(t, operator);
    }

    /**
     * 回收
     */

    @Transactional
    public BaseResponse<T> trash(T t, SysUserEntity operator) {
        if (t == null) throw new FrameworkException("屏蔽失败，请重新选择记录");
        if (operator == null) throw new FrameworkException("屏蔽失败，请重新登录");
        if (t.getActivate() != 1) throw new FrameworkException("屏蔽失败，当前记录已被屏蔽");
        getDAO().trashList(t, operator.getUsername());
        return new BaseResponse<>(BaseResponse.SUCCESS, "屏蔽成功",t);
    }

    /**
     * 批量回收
     */
    @Transactional
    public BaseResponse<List<T>> trashByIds(List<Serializable> ids, SysUserEntity operator) {
        List<T> ts = selectByIds(ids);
        if(ts.size() != ids.size()) throw new FrameworkException("屏蔽失败，请重新选择记录");
        return trashList(ts, operator);
    }

    /**
     * 回收列表
     */
    @Transactional
    public BaseResponse<List<T>> trashList(List<T> ts, SysUserEntity operator) {
        if (CollectionUtils.isEmpty(ts)) throw new FrameworkException("屏蔽失败，请重新选择记录");
        if (operator == null) throw new FrameworkException("屏蔽失败，请重新登录");
        getDAO().trashList(ts, operator.getUsername());
        return new BaseResponse<>(BaseResponse.SUCCESS, "屏蔽成功", ts);
    }

    /**
     * 恢复
     */
    @Transactional
    public BaseResponse<T> recoveryById(String id, SysUserEntity operator) {
        T t = get(id);
        return recovery(t, operator);
    }

    /**
     * 恢复
     */
    @Transactional
    public BaseResponse<T> recovery(T t, SysUserEntity operator) {
        if (t == null) throw new FrameworkException("开启失败，记录不存在");
        if (operator == null) throw new FrameworkException("开启失败，请重新登录");
        if (t.getActivate() == 1) throw new FrameworkException("开启失败，当前记录已开启");
        getDAO().recoveryList(t, operator.getUsername());
        return new BaseResponse<>(BaseResponse.SUCCESS, "开启成功", t);
    }

    /**
     * 恢复列表
     */
    @Transactional
    public BaseResponse<List<T>> recoveryByIds(List<Serializable> ids, SysUserEntity operator) {
        List<T> ts = selectByIds(ids);
        return recoveryList(ts, operator);
    }

    /**
     * 恢复列表
     */
    @Transactional
    public BaseResponse<List<T>> recoveryList(List<T> ts, SysUserEntity operator) {
        if (CollectionUtils.isEmpty(ts)) throw new DAOException("开启失败，请选择记录");
        if (operator == null) throw new DAOException("开启失败，请重新登录");
         getDAO().recoveryList(ts, operator.getUsername());
        return new BaseResponse<>(BaseResponse.SUCCESS, "开启成功", ts);
    }

    /**
     * 物理删除
     */
    @Transactional
    public BaseResponse deleteById(Serializable id) {
        getDAO().deleteById(id);
        return new BaseResponse<>(BaseResponse.SUCCESS, "删除成功");
    }

    @Transactional
    public BaseResponse delete(T t) {
        if (t == null) throw new FrameworkException("删除失败，记录不存在");
        getDAO().delete(t);
        return new BaseResponse<>(BaseResponse.SUCCESS, "删除成功");
    }

    @Transactional
    public BaseResponse deleteByIds(List<Serializable> ids) {
        if (CollectionUtils.isEmpty(ids)) throw new FrameworkException("删除失败，记录不存在");
        getDAO().deleteByIds(ids);
        return new BaseResponse<>(BaseResponse.SUCCESS, "删除成功");
    }

    @Transactional
    public BaseResponse deleteList(List<T> list) {
        if (CollectionUtils.isEmpty(list)) throw new FrameworkException("删除失败，记录不存在");
        getDAO().deleteList(list);
        return new BaseResponse<>(BaseResponse.SUCCESS, "删除成功");
    }


    /**
     * 保存或更新
     */

    public BaseResponse<T> insertOrUpdate(T record, SysUserEntity operator) {
        if (record == null) throw new FrameworkException("保存失败，记录不能为空");
        if (operator == null) throw new FrameworkException("保存失败，操作人不能为空");
        if ( record.getId() != null && getDAO().exists(record.getId())) {
            getDAO().update(record,operator.getUsername());
        } else {
            getDAO().insert(record,operator.getUsername());
        }
        return new BaseResponse<>(BaseResponse.SUCCESS, "保存成功", record);
    }


    public BaseResponse<List<T>> insertOrUpdateList(List<T> records, SysUserEntity operator) {
        if (CollectionUtils.isEmpty(records)) throw new FrameworkException("保存失败，记录不能为空");
        records.forEach(t -> insertOrUpdate(t,operator));
        return new BaseResponse<>(BaseResponse.SUCCESS, "保存成功", records);
    }


    /**
     * 插入，如果存在相同id抛异常
     */

    public BaseResponse<T> insert(T record, SysUserEntity operator) {
        if (record == null) throw new FrameworkException("保存失败，记录不能为空");
        if (operator == null) throw new FrameworkException("保存失败，操作人不能为空");
        getDAO().insert(record, operator.getUsername());
        return new BaseResponse<>(BaseResponse.SUCCESS, "保存成功", record);
    }


    public BaseResponse<List<T>> insertList(List<T> records, SysUserEntity operator) {
        if (CollectionUtils.isEmpty(records)) throw new FrameworkException("保存失败，记录不能为空");
        if (operator == null) throw new FrameworkException("保存失败，操作人不能为空");
        getDAO().insertList(records, operator.getUsername());
        return new BaseResponse<>(BaseResponse.SUCCESS, "保存成功", records);
    }

    /**
     * 更新，如果数据库中没有记录，则抛异常
     */

    public BaseResponse<T> update(T record, SysUserEntity operator) {
        if (record == null) throw new FrameworkException("保存失败，记录不能为空");
        if (operator == null) throw new FrameworkException("保存失败，操作人不能为空");
        getDAO().update(record, operator.getUsername());
        return new BaseResponse<>(BaseResponse.SUCCESS, "保存成功", record);
    }


    public BaseResponse<List<T>> updateList(List<T> records, SysUserEntity operator) {
        if (CollectionUtils.isEmpty(records)) throw new FrameworkException("保存失败，记录不能为空");
        if (operator == null) throw new FrameworkException("保存失败，操作人不能为空");
        getDAO().updateList(records, operator.getUsername());
        return new BaseResponse<>(BaseResponse.SUCCESS, "保存成功", records);
    }

    /**
     * 查找所有实体列表
     *
     * @return 返回实体列表
     */
    public List<T> selectAll() {
        return getDAO().selectAll();
    }

    public List<T> selectByIds(List<Serializable> ids) {
        return getDAO().selectByIds(ids);
    }

    /**
     * 查找所有记录数
     *
     * @return 返回实体记录数
     */
    public long countAll() {
        return getDAO().countAll();
    }

    /**
     * 查询是否存在记录
     */
    public boolean exists(String id) {
        return getDAO().exists(id);
    }

    /**
     * 搜索分页
     * StringMatcher 选项如下
     * CONTAINING ->   LOWER(column) like '%' + LOWER(?) + '%'
     * DEFAULT -> column = ?
     * INSENSITIVE -> LOWER(column) = LOWER(?)
     * 可自定义StringMatcher
     */

    public <S extends PageSearchForm> BasePage<T> queryPage(S searchForm) {
        return genericQueryDAO.queryPage(searchForm, getClazz());
    }


}
